package com.hjh.testdemo.ui.usb.accessory

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbAccessory
import android.hardware.usb.UsbManager
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.hjh.core.activity.BaseFragment
import com.hjh.res.R
import com.hjh.testdemo.databinding.FragmentUsbTestFileBinding
import com.hjh.usb.accessory.UsbConnectionViewModel
import com.hjh.usb.accessory.communication.ConnectionState
import com.hjh.usb.accessory.communication.UsbFlow
import com.hjq.toast.Toaster
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class UsbTestFileFragment : BaseFragment<FragmentUsbTestFileBinding>() {

    private val viewModel: UsbConnectionViewModel by activityViewModels()
    private var currentAccessory: UsbAccessory? = null

    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                UsbManager.ACTION_USB_ACCESSORY_DETACHED -> {
                    val accessory =
                        intent.getParcelableExtra<UsbAccessory>(
                            UsbManager.EXTRA_ACCESSORY
                        )
                    accessory?.let {
                        addLog("设备已断开")
                        binding.connectionStatusTv.text = getString(R.string.status_disconnected)
                        binding.deviceInfoTv.text = getString(R.string.device_info_none)
                        viewModel.disconnect()
                    }
                }

                UsbManager.ACTION_USB_ACCESSORY_ATTACHED -> {
                    val accessory =
                        intent.getParcelableExtra<UsbAccessory>(
                            UsbManager.EXTRA_ACCESSORY,
                        )
                    accessory?.let {
                        addLog("检测到新设备连接")
                        onAccessoryAttached(it)
                    }
                }

                ACTION_USB_PERMISSION -> {
                    synchronized(this) {
                        val accessory =
                            intent.getParcelableExtra<UsbAccessory>(
                                UsbManager.EXTRA_ACCESSORY
                            )
                        val granted =
                            intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                        if (granted) {
                            accessory?.let {
                                addLog("用户授权通过，开始连接设备")
                                viewModel.connectAccessory(it)
                            }
                        } else {
                            addLog("用户拒绝了设备权限")
                            Toaster.show("USB权限被拒绝")
                        }
                    }
                }
            }
        }
    }

    override fun initView() {
        // 设置初始状态
        binding.connectionStatusTv.text = getString(R.string.status_disconnected)
        binding.deviceInfoTv.text = getString(R.string.device_info_none)
    }

    override fun initListener() {
        // 设置按钮点击监听
        binding.sendFileBtn.setOnClickListener {
            val accessory = viewModel.getCurrentAccessory()
            if (accessory == null) {
                Toast.makeText(requireContext(), "设备未连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            sendFile()
        }

        binding.reconnectBtn.setOnClickListener {
            currentAccessory?.let { accessory ->
                addLog("手动重连请求")
                viewModel.connectAccessory(accessory)
            }
        }
    }

    override fun initObserve() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                UsbFlow.usbConnState.collect { state ->
                    updateUI(state)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 注册广播接收器
        val filter = IntentFilter().apply {
            addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED)
            addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED)
            addAction(ACTION_USB_PERMISSION)
        }
        ContextCompat.registerReceiver(
            requireContext(),
            usbReceiver,
            filter,
            ContextCompat.RECEIVER_NOT_EXPORTED
        )

        // 检查已连接的附件
        checkConnectedAccessories()
    }

    override fun onPause() {
        super.onPause()
        // 注销广播接收器
        requireContext().unregisterReceiver(usbReceiver)
    }

    private fun checkConnectedAccessories() {
        val usbManager = requireContext().getSystemService(Context.USB_SERVICE) as UsbManager
        val accessoryList = usbManager.accessoryList

        accessoryList?.firstOrNull()?.let { accessory ->
            addLog("发现已连接的设备: ${accessory.model}")
            onAccessoryAttached(accessory)
        } ?: run {
            addLog("未检测到连接的USB设备")
        }
    }

    private fun onAccessoryAttached(accessory: UsbAccessory) {
        currentAccessory = accessory

        val usbManager = requireContext().getSystemService(Context.USB_SERVICE) as UsbManager
        if (usbManager.hasPermission(accessory)) {
            addLog("已获得设备权限，正在连接...")
            viewModel.connectAccessory(accessory)
        } else {
            addLog("请求设备权限...")
            requestPermission(accessory)
        }
    }

    private fun requestPermission(accessory: UsbAccessory) {
        val usbManager = requireContext().getSystemService(Context.USB_SERVICE) as UsbManager
        val permissionIntent = PendingIntent.getBroadcast(
            requireContext(),
            0,
            Intent(ACTION_USB_PERMISSION),
            PendingIntent.FLAG_IMMUTABLE
        )
        usbManager.requestPermission(accessory, permissionIntent)
    }

    private fun updateUI(state: ConnectionState) {
        when (state) {
            is ConnectionState.Disconnected -> {
                binding.connectionStatusTv.text = getString(R.string.status_disconnected)
                binding.deviceInfoTv.text = getString(R.string.device_info_none)
                binding.reconnectInfoTv.visibility = View.GONE
                binding.reconnectBtn.visibility = View.GONE
                binding.sendFileBtn.isEnabled = false
                binding.progressBar.visibility = View.GONE
            }

            is ConnectionState.Connecting -> {
                binding.connectionStatusTv.text = getString(R.string.status_connecting)
                binding.deviceInfoTv.text = "设备: ${currentAccessory?.model ?: "未知"}"
                binding.reconnectInfoTv.visibility = View.GONE
                binding.reconnectBtn.visibility = View.GONE
                binding.sendFileBtn.isEnabled = false
                binding.progressBar.visibility = View.VISIBLE
                addLog(getString(R.string.log_connecting))
            }

            is ConnectionState.Connected -> {
                binding.connectionStatusTv.text = getString(R.string.status_connected)
                binding.deviceInfoTv.text = "设备: ${state.accessory.model}"
                binding.reconnectInfoTv.visibility = View.GONE
                binding.reconnectBtn.visibility = View.GONE
                binding.sendFileBtn.isEnabled = true
                binding.progressBar.visibility = View.GONE
                addLog(getString(R.string.log_connected, state.accessory.model))
            }

            is ConnectionState.Reconnecting -> {
                binding.connectionStatusTv.text = getString(R.string.status_reconnecting)
                binding.deviceInfoTv.text = "设备: ${currentAccessory?.model ?: "未知"}"
                binding.reconnectInfoTv.text = "重连次数: ${state.retryCount}"
                binding.reconnectInfoTv.visibility = View.VISIBLE
                binding.reconnectBtn.visibility = View.VISIBLE
                binding.sendFileBtn.isEnabled = false
                binding.progressBar.visibility = View.VISIBLE
                addLog(getString(R.string.log_reconnecting, state.retryCount))
            }

            is ConnectionState.Error -> {
                binding.connectionStatusTv.text = getString(R.string.status_error)
                binding.deviceInfoTv.text = "设备: ${currentAccessory?.model ?: "未知"}"
                binding.reconnectInfoTv.text = "错误: ${state.message}"
                binding.reconnectInfoTv.visibility = View.VISIBLE
                binding.reconnectBtn.visibility = View.VISIBLE
                binding.sendFileBtn.isEnabled = false
                binding.progressBar.visibility = View.GONE
                addLog(getString(R.string.log_error, state.message))
            }
        }
    }

    private fun sendFile() {
        // 这里简化处理，实际应用中应该让用户选择文件
        val filePath = "Movies/test_515MB.mp4"
        addLog(getString(R.string.log_sending, filePath))
        binding.progressBar.visibility = View.VISIBLE
        binding.sendFileBtn.isEnabled = false

        sendFile(filePath)
    }

    private fun addLog(message: String) {
        val timestamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
        val logEntry = "$timestamp: $message\n"

        binding.logTv.append(logEntry)

        // 自动滚动到底部
        val scrollView = binding.logTv.parent as? NestedScrollView
        scrollView?.post {
            scrollView.fullScroll(View.FOCUS_DOWN)
        }
    }

    private fun sendFile(filePath: String) {
        binding.progressBar.visibility = View.VISIBLE
        binding.sendFileBtn.isEnabled = false

        viewModel.aoaService?.sendFile(filePath) { success ->
            requireActivity().runOnUiThread {
                binding.progressBar.visibility = View.GONE
                binding.sendFileBtn.isEnabled = true

                if (success) {
                    Toast.makeText(requireContext(), "文件发送成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(requireContext(), "文件发送失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    companion object {
        const val ACTION_USB_PERMISSION = "com.hjh.usb.USB_PERMISSION"
    }
}